package com.hrm.controller;

import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.hrm.config.QiNiuConfig;
import com.hrm.pojo.Document;
import com.hrm.pojo.Notice;
import com.hrm.pojo.dto.FileList;
import com.hrm.service.DocumentService;
import com.hrm.utils.entity.Result;
import com.hrm.utils.entity.StatusCode;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.net.URLEncoder;

@RestController
@CrossOrigin
@RequestMapping("/document")
@Api(tags = "下载中心的接口")
public class DocumentController {
    @Autowired
    private DocumentService documentService;
    @Autowired
    private QiNiuConfig qiNiuConfig;
    @Autowired
    private HttpServletRequest request;
    @PostMapping("/upload")
    @ApiOperation(value = "文档上传")
    public Result uploadDocument(MultipartFile file) throws Exception {
        System.out.println(file.getOriginalFilename());
        //获取token中的用户id
        Integer id = Integer.parseInt((String) request.getSession().getAttribute("id"));
        String fileName = id + "_" +file.getOriginalFilename();
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
            String upToken = auth.uploadToken(qiNiuConfig.getBucket());
            try {
                Response response = uploadManager.put(uploadBytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            } catch (QiniuException ex) {
                throw new Exception("异常信息："+ex);
            }
        } catch (UnsupportedEncodingException ex) {
            throw new Exception("编码异常！");
        }
        return new Result(true, StatusCode.SUCCESS, "上传成功！",key);
    }

    @PostMapping("/add")
    @ApiOperation(value = "文档数据添加")
    public Result addDocument(@RequestBody Document document) throws Exception {
        boolean flag = documentService.addDocument(document);
        if (!flag) {
            throw new Exception("添加失败！");
        }
        return new Result(flag, StatusCode.SUCCESS, "添加成功！");
    }

    @PostMapping("/list")
    @ApiOperation(value = "文档数据展示")
    public Result findFileList(@RequestBody FileList fileList)throws Exception{
        List<Document> documentList = documentService.findByTitle(fileList.getPageNum(), fileList.getPageSize(), fileList.getTitle());
        if(documentList==null || documentList.isEmpty()){
            return new Result(false, StatusCode.ERROR,"获取文档分页数据失败");
        }
        PageInfo<Document> pageInfo=new PageInfo<>(documentList,10);
        return  new Result(true, StatusCode.SUCCESS,"获取文档列表数据成功",pageInfo);
    }

    //查询单个文档
    @GetMapping("/show/{id}")
    @ApiOperation(value ="单个文档查询")
    public Result prviewNotice(@PathVariable Integer id)throws Exception{
        Document document = documentService.findById(id);
        if(document==null){
            return new Result(false,StatusCode.ERROR,"查询失败");
        }
        return new Result(true, StatusCode.SUCCESS,"查询成功",document);
    }

    @PutMapping("/update")
    @ApiOperation(value = "文档数据更新")
    public Result updateDocument(@RequestBody Document document) throws Exception {
        boolean flag = documentService.updateDocument(document);
        if (!flag) {
            throw new Exception("更新失败！");
        }
        return new Result(flag, StatusCode.SUCCESS, "更新成功！");
    }

    @PostMapping("download")
    @ApiOperation(value = "文档下载")
    public void downDocument(HttpServletResponse response, @RequestParam("filename") String filename) throws Exception {
        String encodedFileName = URLEncoder.encode(filename, "utf-8").replace("+", "%20");
        String publicUrl = String.format("%s/%s", qiNiuConfig.getDomainOfBucket(), encodedFileName);
        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
        long expireInSeconds = 3600; // 1小时，可以自定义链接过期时间
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);

        // 设置响应的Content-Disposition头
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
        response.setContentType("application/octet-stream");

        try (InputStream in = new URL(finalUrl).openStream();
             OutputStream out = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            // 将文件流写入响应流
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush(); // 确保输出流被刷新
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        }
    }

    //删除文档
    @DeleteMapping("/delete")
    @ApiOperation(value = "删除文档")
    public Result deleteDocument(@RequestBody ArrayList<Integer> documentIdList)throws Exception{
        boolean flag=documentService.deleteDocument(documentIdList);
        return new Result(flag,flag==true? StatusCode.SUCCESS:StatusCode.ERROR,flag==true?"删除成功":"删除失败");
    }


}
